import React, { useEffect, useState } from 'react';
import { PlusOutlined, CaretUpOutlined, CaretDownOutlined, LoadingOutlined } from '@ant-design/icons';
import type { RadioChangeEvent } from 'antd';
import {
    Form,
    Input,
    Button,
    Select,
    DatePicker,
    InputNumber,
    TreeSelect,
    Switch,
    Checkbox,
    Upload,
    Collapse,
    Radio,
    Tabs,
    Table,
    message,
    Modal
} from 'antd';
import type { ColumnsType } from 'antd/es/table';
import type { UploadChangeParam } from 'antd/es/upload';
import type { RcFile, UploadFile, UploadProps } from 'antd/es/upload/interface';
import { foodClass, getRestFoodsClass, addFoodsClass, addFoodsApi } from "../../api/request"
import "./AddGoods.scss"
import { useNavigate } from 'react-router-dom';
const { Option } = Select;

const { RangePicker } = DatePicker;
const { TextArea } = Input;



const FormDisabledDemo = () => {
    const Navigate = useNavigate()
    const { Panel } = Collapse;
    const [value, setValue] = useState(1);
    const text = `
  A dog is a type of domesticated animal`;
    const onChange = (key: string | string[]) => {
        console.log(key);
    };
    const onTabChange = (key: string) => {
        console.log(key);
    };
    const onRadioChange = (e: RadioChangeEvent) => {
        console.log('radio checked', e.target.value);
        setValue(e.target.value);
    };
    const children: React.ReactNode[] = [];

    children.push(<Option key={1}>新品</Option>);
    children.push(<Option key={2}>招牌</Option>);

    const columns = [
        { title: '规格', dataIndex: 'name', key: 'name' },
        { title: '包装费', dataIndex: 'age', key: 'age' },
        { title: '价格', dataIndex: 'address', key: 'address' },
        {
            title: '操作',
            dataIndex: '',
            key: 'x',
            render: () => <Button type="primary" danger style={{
                borderRadius: 5
            }}>删除</Button>,
        },
    ];

    const datas: any = [
        {
            key: 1,
            name: '默认',
            age: 0,
            address: 20,
        },
    ];

    const [restFoodClass, setRestFoodsClass]: any = useState([])
    const RestId = localStorage.getItem("restaurant_id")
    useEffect(() => {
        //获取当前店铺食种类
        getRestFoodsClass(RestId).then((res) => {
            // console.log(res.data.category_list)
            if (res.data.category_list) {
                setRestFoodsClass(() => res.data.category_list.map((item: any) => {
                    return {
                        name: item.name,
                        id: item.id
                    }
                }))
            }

        })

    }, [])

    // console.log(restFoodClass);
    const RadioEl = (value: any) => {
        if (value == 1) {
            return (
                <>
                    {/* <Form> */}
                    <Form.Item label="包装费" initialValue={2} name="packing_fee">
                        <InputNumber min={0} max={10000} controls={{
                            upIcon: <CaretUpOutlined />,
                            downIcon: <CaretDownOutlined />
                        }} />
                    </Form.Item>
                    <Form.Item label="价格" initialValue={20} name="price">
                        <InputNumber min={0} max={10000} controls={{
                            upIcon: <CaretUpOutlined />,
                            downIcon: <CaretDownOutlined />
                        }} />
                    </Form.Item>
                    {/* </Form> */}

                </>
            )
        } else {
            return (
                <>
                    <Button type="primary" style={{
                        marginLeft: "350px",
                        marginBottom: "10px",
                        borderRadius: 5
                    }}>添加规格</Button>
                    <Table
                        columns={columns}
                        expandable={{
                            rowExpandable: record => record.name !== 'Not Expandable',
                        }}
                        dataSource={datas}
                        pagination={false}
                        style={{
                            marginLeft: 10,
                            marginRight: 10
                        }}
                    />
                </>
            )
        }
    }

    const summitFoods = (values: any) => {
        console.log(values);
        const data = {
            ...values,
            restaurant_id: RestId
        }
        addFoodsClass(data).then((res) => {
            console.log(res);
            if (res.status == 1) {
                message.success(res.success)
                window.location.reload()
            } else {
                message.error(res.message)
            }

        })
    }
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    const getBase64 = (img: RcFile, callback: (url: string) => void) => {
        const reader = new FileReader();
        reader.addEventListener('load', () => callback(reader.result as string));
        reader.readAsDataURL(img);
    };
    const uploadButton = (
        <div>
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </div>
    );

    const beforeUpload = (file: RcFile) => {
        const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png';
        if (!isJpgOrPng) {
            message.error('You can only upload JPG/PNG file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 2;
        if (!isLt2M) {
            message.error('Image must smaller than 2MB!');
        }
        return isJpgOrPng && isLt2M;
    };

    const handleChange: UploadProps['onChange'] = (info: UploadChangeParam<UploadFile>) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done' && info.file.response) {
            // Get this url from response in real world.
            getBase64(info.file.originFileObj as RcFile, url => {
                setLoading(false);
                setImageUrl(() => info.file.response.image_path);
            });
        }
    };
    const [categoryID, setCategoryID] = useState()
    const getcategoryID = (values: any) => {
        console.log(values);
        setCategoryID(values)
    }

    const addFoods = (values: any) => {
        // console.log(1111111111, values);
        if (!imageUrl) {
            message.warning("请上传图片")
        } else if (!values.attributes) {
            message.warning("请选择食品特点")
        } else if (!RestId) {
            message.warning("添加食品需要选择餐馆")
        } else if (!categoryID) {
            message.warning("请选择食品种类")
        } else {
            const data = {
                ...values,
                attributes: [values.attributes],
                restaurant_id: RestId,
                category_id: categoryID,
                image_path: imageUrl,
                specs: [{ specs: '默认', packing_fee: 20, price: 2000, }]
            }
            console.log(data);
            addFoodsApi(data).then((res) => {
                // console.log(22222222222, res);
                if (res.status == 1) {
                    message.success("添加成功")
                    window.location.reload()
                }

            })

        }

    }

    const bool = localStorage.getItem("restaurant_id") ? false : true
    const [isModalOpen, setIsModalOpen] = useState(bool);
    const showModal = () => {
        setIsModalOpen(true);
    };

    const handleOk1 = () => {
        setIsModalOpen(false);
        Navigate("/admin/restaurant")
    };

    const handleCancel1 = () => {
        setIsModalOpen(false);
        message.error("取消成功")
    };

    return (
        <div style={{
            width: 1100,
            margin: "auto"
        }}>
            <h3 style={{
                textAlign: "center",
                marginTop: 20,
                marginBottom: 10,
            }}>选择食品种类</h3>
            <div style={{
                width: 800,
                margin: "auto",
                border: "1px solid #dbdbdb"
            }}>
                <Form>
                    <Form.Item rules={[{ required: true }]} label="食品种类" style={{
                        width: 700,
                        margin: "20px auto"
                    }}>
                        <Select onChange={getcategoryID}>
                            {
                                restFoodClass.map((item: any, index: number) => {
                                    return (
                                        <Select.Option value={item.id} key={index}>{item.name}</Select.Option>
                                    )
                                })
                            }
                        </Select>
                    </Form.Item>
                </Form>

                <Collapse defaultActiveKey={[]} onChange={onChange} expandIconPosition="end">
                    <Panel header="添加食品种类" key="1" style={{
                        textAlign: "center"
                    }}>
                        <Form
                            labelCol={{ span: 3 }}
                            wrapperCol={{ span: 20 }}
                            layout="horizontal"
                            onFinish={summitFoods}
                            style={{
                                padding: 0
                            }}>
                            <Form.Item label="食品种类" name="name" rules={[{ required: true }]}>
                                <Input />
                            </Form.Item>
                            <Form.Item label="种类描述" name="description">
                                <Input />
                            </Form.Item>
                            <Form.Item label="">
                                <Button type="primary" htmlType="submit" style={{
                                    borderRadius: 5,
                                    marginLeft: 80
                                }}>提交</Button>
                            </Form.Item>
                        </Form>
                    </Panel>
                </Collapse>
            </div>
            <h3 style={{
                textAlign: "center",
                marginTop: 20,
                marginBottom: 10,
            }}>添加食品</h3>
            <div style={{
                width: 800,
                margin: "auto",
                border: "1px solid #dbdbdb"
            }}>
                <Form
                    labelCol={{ span: 3 }}
                    wrapperCol={{ span: 20 }}
                    layout="horizontal"
                    onFinish={addFoods}
                    style={{
                        marginTop: 10
                    }}
                >
                    <Form.Item label="食品名称" name="name" rules={[{ required: true }]}>
                        <Input />
                    </Form.Item>
                    <Form.Item label="食品活动" name="activity" >
                        <Input />
                    </Form.Item>
                    <Form.Item label="食品详情" name="description">
                        <Input />
                    </Form.Item>
                    <Form.Item label="上传食品图片" valuePropName="fileList" >
                        <Upload
                            name="file"
                            listType="picture-card"
                            className="avatar-uploader"
                            showUploadList={false}
                            action="/v1/addimg/shop"
                            beforeUpload={beforeUpload}
                            onChange={handleChange}
                        >
                            {imageUrl ? <img src={'//elm.cangdu.org/img/' + imageUrl} alt="avatar" style={{ width: 120, height: 100 }} /> : uploadButton}
                        </Upload>
                    </Form.Item>
                    <Form.Item label="食品特点" name="attributes" >
                        <Select placeholder="请选择" style={{
                            width: 200
                        }}>
                            <Select.Option value="新品">新品</Select.Option>
                            <Select.Option value="招牌">招牌</Select.Option>
                        </Select>
                    </Form.Item>
                    <Form.Item label="食品规格" name='specs' initialValue={value} rules={[{ required: true }]}>
                        <Radio.Group onChange={onRadioChange} value={value} >
                            <Radio value={1}>单规格</Radio>
                            <Radio value={2}>多规格</Radio>
                        </Radio.Group>
                    </Form.Item>
                    {
                        RadioEl(value)
                    }
                    <Form.Item label="提交" style={{
                        marginTop: 20
                    }}>
                        <Button type="primary" htmlType="submit" style={{
                            borderRadius: 5
                        }}>确认添加食品</Button>
                    </Form.Item>
                </Form>
                <Modal title="提示" open={isModalOpen} onOk={handleOk1} onCancel={handleCancel1}>
                    <p>添加食品需要选择一个商铺，先去就去选择商铺吗？</p>
                </Modal>
            </div>
        </div >
    );
};

export default () => <FormDisabledDemo />;